const app = getApp();
const axios = require('../../utils/axios');

Page({
  data: {
    user: app.globalData.user,
    data: {}
  },

  onLoad(options) {

  },
  
  onInput(e) {
    const { key } = e.currentTarget.dataset;
    const name = 'data.' + key;
    this.setData({ [name]: e.detail.value });
  },

  onConfirm() {
    function Toast(title) {
      wx.showToast({
        title,
        icon: 'error',
        duration: 1500,
        mask: true
      });
      return false;
    }
    function check(data) {
      if(!data.cName) {
        return Toast('请输入企业名称');
      } else if (!data.licenseId) {
        return Toast('请输入执照号码');
      } else if (!data.bankId) {
        return Toast('请输入对公账户卡号');
      } else if (!data.capacity) {
        return Toast('请输入企业规模人数');
      } else if (!data.content) {
        return Toast('请输入企业介绍');
      }
      return true;
    }

    const { user, data } = this.data;
    if(!check(data)) {
      return;
    }

    const header = app.globalData.header;
    axios.post('/company', { ...data, id: user.id }, header).then(res => {
      const { code, data, err } = res;
      if(code == 200) {
        console.log(data);
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1500,
          mask: true
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else if (code == 401) {
        app.login(() => this.onConfirm());
      } else throw err;
    }).catch(err => {
      wx.showModal({
        title: '错误',
        content: JSON.stringify(err),
        showCancel: false
      });
    });
  },
})